import React from 'react'
import "./less/Means.less"
import { Button, Form, Input, message, Upload } from 'antd';
import {GetUserDataApi,ChangeUserDataApi} from '../request/api'
import { useEffect } from 'react';
import { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
// import {useNavigate} from 'react-router-dom'

export default function Means() {
  // const navgate = useNavigate()
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');

//点击了上传图片
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // console.log(info.file.response.data.filePath);
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl) => {
        setLoading(false);
        setImageUrl(imageUrl);
        //存储图片名称
        localStorage.setItem('avatar',info.file.response.data.filePath)
        //header组件那边监听更新
        window.location.reload() // 强制页面刷新
      });
    }
  };
//上传图片大小规范
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 / 1024  < 200;
    if (!isLt2M) {
      message.error('请上传小于200KB的图片!');
    }
    return isJpgOrPng && isLt2M;
  };
//将图片转换为Base64
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
//上传按钮
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );

  useEffect(()=>{
    GetUserDataApi().then(res=>{
      console.log(res);
      if(res.errCode===0){
        message.success(res.message)
        //存到sessionStorage
        sessionStorage.setItem('nameong',res.data.username)
        // console.log(res.data.username);
      }
    })
  },[])

  //表单提交的事件
  const onFinish = (values)=>{
    //如果表单的username有值 并且不等于初始化时拿到的usename,并且密码非空
    if(values.username && values.username !== sessionStorage.getItem('username') && values.password.trim() !== ''){
      //做表单提交操作...
      ChangeUserDataApi({
        nameong: values.username,
        password: values.password
      }).then(res=>{
        console.log(res);
        //当修改成功后跳到重新登录
        // navgate('/login')
      })
    }
  }

  return (
    <div className='means'>
      <Form
        name="basic"
        style={{width:'400px'}}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item label="修改用户名" name="username">
          <Input placeholder='请输入新用户名' />
        </Form.Item>

        <Form.Item label="修 改 密 码" name="password">
          <Input.Password placeholder='请输入新密码' />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit" style={{float:'right'}}>提交</Button>
        </Form.Item>
      </Form>
      <p>点击下方修改头像:</p>
      <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="/api/upload"
      beforeUpload={beforeUpload}
      onChange={handleChange}
      // 在Upload组件身上携带token
      headers={{"cms-token": localStorage.getItem('cms-token')}}
    >
      {/* 有图片路径就用没有就显示上传图片按钮 */}
      {imageUrl ? (<img src={imageUrl} alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
    </div>
  )
}
